package com.tengju.bff.interfaces.covercharge.service.bestsign.util;

import com.tengju.bff.interfaces.covercharge.entity.dto.HttpClientResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author liang_shi
 * @date 2020/7/13 14:52
 * @description 请求响应
 */
@Slf4j
public class HttpResponseHandler implements ResponseHandler<HttpClientResponse> {

    @Override
    public HttpClientResponse handleResponse(HttpResponse response) throws IOException {
        final StatusLine statusLine = response.getStatusLine();
        final HttpEntity entity = response.getEntity();
        //结果响应
        HttpClientResponse httpResponse = new HttpClientResponse();
        int code = statusLine.getStatusCode();
        httpResponse.setCode(code);
        httpResponse.setContent("");
        if (code != 200) {
            String errMsg;
            if (!Objects.isNull(entity)) {
                errMsg = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                httpResponse.setErrMsg(errMsg);
            }
        } else {
            if (!Objects.isNull(entity)) {
                byte[] responseBody = EntityUtils.toByteArray(entity);
                httpResponse.setContent(new String(responseBody, StandardCharsets.UTF_8));
                httpResponse.setContentByte(responseBody);
            }
        }
        EntityUtils.consume(entity);
        return httpResponse;
    }
}
